# -*- coding: utf-8 -*
import re
import subprocess

from ..common import Collector


class ContextSwitchCollector(Collector):
    """上下文切换次数收集器"""
    def __init__(self, is_test):
        super().__init__(is_test)

    def collect(self) -> None:
        if self.is_test:
            test_file_path = Collector.get_test_file_path("vmstat.txt", __file__)
            with open(test_file_path, "r", encoding="utf-8") as f:
                lines = f.readlines()
                tail_line = lines[-1].strip()

            pat = re.compile(r"\s+")
            val_list = pat.sub(" ", tail_line).split(" ")
        else:
            process_out = subprocess.run(["vmstat", "1", "2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out_str = str(process_out.stdout, encoding="utf-8")

            pat = re.compile(r"\s+")
            space_out_str = pat.sub(" ", out_str)
            number_pat = re.compile(r"\d+")
            val_list = number_pat.findall(space_out_str)

        val_list = list(map(float, val_list))
        cs = val_list[-6]
        self.stash.append(cs)
